<template>
<l-fullscreen-dialog
    :title="`${$t('发起流程')}【${title}】`"
    :visible.sync="midVisible"
    :showOk="false"

    @closed="handleClosed"
    @opened="handleOpened"

    ref="formDialog"
    >
    <template #headerRight >
        <el-button-group style="margin-right:8px;" >
            <el-button @click="handleCreateFlow" type="primary" size="mini" >发起流程</el-button>
            <el-button v-if="isDraftBtn" @click="handleSaveDraft" size="mini">保存草稿</el-button>
        </el-button-group>
    </template>

    <l-layout class="l-tab-page" :right="320" >
        <l-panel :style="{'padding-right':(isCustmerTitle || (delegateUsers && delegateUsers.length>0))?0:null}" >
            <div class="l-auto-window" style="padding: 0 8px;"  >
                <el-tabs v-model="activeName" @tab-click="handleTabClick" >
                    <el-tab-pane v-if="hasWfForm" :label="$t('表单信息')" name="form">
                        <div class="l-rblock" v-loading="formSchemeLoding">
                            <template v-if="showForm" >
                                <l-form-viewer 
                                    v-if="formType == '1'"
                                    :formInfo="formInfo"
                                    :isWfForm="true"
                                    :authFieldsMap="formAuthFieldsMap"
                                    ref="wfForm"
                                ></l-form-viewer>
                                <component ref="wfForm" v-else :requiredMap="formRequiredMap" :authFieldsMap="formAuthFieldsMap" :isWfForm="true" :is="sysFormComponent"></component>
                            </template>
                        </div>
                    </el-tab-pane>
                    <el-tab-pane :label="$t('流程信息')" name="wfinfo">
                        <l-layout style="background: #f1f2f5;">
                            <l-panel class="flow-panel" style="padding:0;padding-top:0;" >
                                <template #title>
                                    <el-button-group>
                                        <el-tooltip effect="dark" :content="$t('复原')" placement="bottom">
                                            <el-button  size="mini" icon="el-icon-aim" @click="resetZoom"></el-button>
                                        </el-tooltip>
                                        <el-tooltip effect="dark" :content="$t('放大')" placement="bottom">
                                            <el-button  size="mini" icon="el-icon-zoom-in" @click="handlerZoom(0.1)"></el-button>
                                        </el-tooltip>
                                        <el-tooltip effect="dark" :content="$t('缩小')" placement="bottom">
                                            <el-button  size="mini" icon="el-icon-zoom-out" @click="handlerZoom(-0.1)"></el-button>
                                        </el-tooltip>
                                    </el-button-group>
                                </template>
                                <b-wflow-viewer
                                    ref="bflow" 
                                    @elementClick="elementClick"
                                    >
                                </b-wflow-viewer>
                            </l-panel>
                        </l-layout>
                    </el-tab-pane>
                </el-tabs>
            </div>
        </l-panel>
        <template #right  >
            <l-panel v-if="isCustmerTitle || (delegateUsers && delegateUsers.length >0)" title="填写信息" style="padding-left:0;">
                <div class="l-rblock" style="padding:8px;" >
                   <el-form :model="formData" :rules="rules" size="mini"  ref="form" >
                        <el-form-item label="流程标题" prop="title" v-if="isCustmerTitle">
                            <el-input 
                                v-model="formData.title"
                                placeholder="请输入"
                                >
                            </el-input>
                        </el-form-item>
                        <el-form-item v-if="delegateUsers && delegateUsers.length >0" label="流程发起人" prop="userId">
                            <l-select 
                                valueKey="f_UserId"
                                labelKey="f_RealName"
                                :options="delegateUsers"
                                v-model="formData.userId"
                                ></l-select>
                        </el-form-item>                        
                    </el-form>
                </div>
            </l-panel>
        </template>
    </l-layout>

    <l-dialog   
        :width="500"
        :height="nodeUsers.length * 48 + 88"
        title="选择下一审核节点人员"
        :visible.sync="selectUsersVisible"
        @ok="handleSelectUsersSave"
        @close="handleSelectUsersCloseForm"

        :showClose="false"
        >
        <select-users ref="selectUsers" :nodeList="nodeUsers"></select-users>
    </l-dialog>
</l-fullscreen-dialog>
</template>

<script>
import mixin from '../../mixins/wf'
import SelectUsers from '../task/process/selectAuditUsers.vue'

const api = window.$api.workflow.process
const apiDelegate = window.$api.workflow.delegate 
export default {
    mixins:[mixin()],
    props:{
        isDraftBtn:{
            type:Boolean,
            default:true
        }
    },
    components:{
        SelectUsers
    },
    data () {
        return {
            midVisible:false,
            isCustmerTitle:false,            

            formData:{
                userId:'',
                title:''
            },
            rules:{
                title:[
                    { required: true, message: '请选择流程标题',trigger: 'blur' }
                ],
                userId: [
                    { required: true, message: '请选择流程发起人',trigger: 'blur' }
                ],
            },

            nodeUsers:[],
            selectUsersVisible:false,

            isDraft:false


        }
    },

    computed:{
    },
    asyncComputed:{
      delegateUsers:{
        async get(){
            if(this.code){
                const data = await this.$awaitWraper(apiDelegate.getMyUserList(this.code))
                if(data && data.length >0){
                    data.push(this.loginInfo)
                }
                return data || []
            }
            return []
            
        }
      }
    },
    watch:{
        visible: {
            handler (n) {
                this.midVisible = n
            }
        },
    },
    mounted () {
    },
    
    
    methods:{
        resetZoom(){
            this.$refs.bflow.reset()
        },
        handlerZoom(r){
            this.$refs.bflow.handlerZoom(r)
        },
        elementClick(){
        },
        resetFormToMe(){
            this.isDraft = false
            this.$refs.form && this.$refs.form.resetFields()
        },
        setForm(){
            this.formData.userId = this.loginInfo.f_UserId
            this.currentNode = this.wfData.find(t=>t.type == 'startEvent')
            this.isCustmerTitle = this.currentNode.isCustmerTitle
            if(this.isCustmerTitle && this.type == 'draft'){
                this.formData.title = this.process.f_Title
            }
        },
        validateForm(){
            return this.$formValidateWraper(this.$refs.form)
        },
        async handleSaveDraft(){
            if(!(await this.validateForm())){
                return
            }
            this.$refs.formDialog.showLoading('保存草稿中...')
            if(!(await this.saveWfForm('draft'))){
                this.$refs.formDialog.hideLoading()
                return 
            }

            const wfData = {
                processId:this.processId,
                schemeCode:this.code,
                userId:this.formData.userId,
                title:this.formData.title
            }
            await api.saveDraft(wfData)

            this.isDraft = true
            this.$message({
                type: 'success',
                message: this.$t('保存成功!')
            })
            this.$refs.formDialog.hideLoading()

            this.$emit('refresh')
        },
        async handleCreateFlow(){
            this.$refs.formDialog.showLoading('创建流程...')

            if(!(await this.validateForm())){
                this.$refs.formDialog.hideLoading()
                return
            }

            if(!(await this.validateWfForm())){
                this.$refs.formDialog.hideLoading()
                return
            }

            if(!(await this.saveWfForm('create'))){
                this.$refs.formDialog.hideLoading()
                return 
            }
            
            // 创建流程
            const wfData = {
                processId:this.processId,
                schemeCode:this.isDraft?'':this.code,
                userId:this.formData.userId,
                title:this.formData.title
            }

            if(!this.isDraft){
                await api.saveDraft(wfData)
                wfData.schemeCode = ''
                this.isDraft = true
            }
            
            // 获取接下来节点审核人
            if(this.currentNode.isNextAuditor){
                const res = await api.getNextUsers({code:wfData.schemeCode, processId:this.processId,nodeId:this.currentNode.id})
                const nodeUserMap = res.data.data
                const nodeUsers = []
                for(let key in nodeUserMap){
                    const nodeUserItem = nodeUserMap[key]
                    if(nodeUserItem.length > 1){
                        nodeUsers.push({
                            name:this.wfData.find(t=>t.id == key).name,
                            id:key,
                            options:nodeUserItem.map(t=>{return{value:t.id,label:t.name} })
                        })
                    }
                }

                this.nodeUsers = nodeUsers

                if(this.nodeUsers.length > 0){
                    this.selectUsersVisible = true
                    this.$refs.formDialog.hideLoading()
                    return
                }
            }
            
            await api.create(wfData)
            this.$message({
                type: 'success',
                message: this.$t('创建成功!')
            })
            this.midVisible = false

            this.$refs.formDialog.hideLoading()

            this.$emit('refresh')
        },
        async handleSelectUsersSave(){
            this.selectUsersVisible = false
            this.$refs.formDialog.showLoading('创建流程...')

             // 创建流程
            const wfData = {
                processId:this.processId,
                schemeCode:this.isDraft?'':this.code,
                userId:this.formData.userId,
                title:this.formData.title,
                nextUsers: this.$refs.selectUsers.getForm() 
            }

            await api.create(wfData)
            this.$message({
                type: 'success',
                message: this.$t('创建成功!')
            })
            this.midVisible = false

            this.$refs.formDialog.hideLoading()

            this.$emit('refresh')
        },
        handleSelectUsersCloseForm(){
            this.$refs.selectUsers.resetForm()
        }
    }
}
</script>